/* eslint-disable react-hooks/exhaustive-deps */
import { FC, memo, useEffect, useState } from 'react'
import { Prism as SyntaxHighlighter } from 'react-syntax-highlighter'
// import { solarizedlight } from 'react-syntax-highlighter/dist/esm/styles/prism'
import { UpkeepDetailWrapper, UpkeepWrapper } from './style'
import { shallowEqualApp, useAppDispatch, useAppSelector } from '@/store'
import { fetchUpkeepListAction } from '@/store/module/upkeep'
import { formatTime } from '@/utils/time'
import LtDrawer from '@/base-ui/lt-drawer'

interface IState {
  children?: React.ReactNode
}

const Upkeep: FC<IState> = memo(() => {
  const dispatch = useAppDispatch()

  // 获得列表数据
  const [page, setPage] = useState(1)
  const [upkeepList, setUpkeepList] = useState<any>([])
  useEffect(() => {
    dispatch(fetchUpkeepListAction({ page })).then((res: any) => {
      if (res.payload.length === 5) {
        setMoreText('加载更多...')
      } else {
        setMoreText('没有更多了')
      }
      setUpkeepList(res.payload)
    })
  }, [])

  const { theme } = useAppSelector(
    (state) => ({
      theme: state.options.theme
    }),
    shallowEqualApp
  )

  // 监听主题变化
  const [themeColor, setThemeColor] = useState<string>(theme)
  useEffect(() => {
    if (theme === 'theme-light') {
      setThemeColor('#fff')
    } else {
      setThemeColor('#202025')
    }
  }, [theme])

  // 渲染upkeep列表
  const renderUpkeepList = () => {
    return upkeepList.map((item: any) => {
      return (
        <div className="upkeep_item" key={item.id} onClick={() => lookDetail(item)}>
          <div className="poster">
            <img src={item.poster} alt="poster" />
          </div>
          <div className="right">
            <div className="title">{item.title}</div>
            <div className="desc">{item.desc}</div>
            <div className="bottom">
              <div className="tag">
                {item.tag?.map((m: string) => {
                  return (
                    <span className="tag_item" key={m}>
                      {m}
                    </span>
                  )
                })}
              </div>
              <div className="time">
                <span>{formatTime(item.created_at)}</span>
              </div>
            </div>
          </div>
        </div>
      )
    })
  }

  // 查看详情
  const [detail, setDetail] = useState<any>({})
  const [open, setOpen] = useState(false)
  const lookDetail = (item: any) => {
    setOpen(true)
    setDetail(item)
  }

  // 检查是否到达页面底部
  const isBottomOfPage = (event: React.UIEvent<HTMLElement>) => {
    const { scrollTop, offsetHeight, scrollHeight } = event.currentTarget
    return scrollTop + offsetHeight >= scrollHeight
  }

  // 滚动页面
  const [moreText, setMoreText] = useState('加载更多...')
  const scrollPageHandle = (event: React.UIEvent<HTMLElement>) => {
    if (isBottomOfPage(event) && moreText === '加载更多...') {
      setMoreText('加载中...')
      setPage(page + 1)
      dispatch(fetchUpkeepListAction({ page: page + 1 })).then((res: any) => {
        if (res.payload.length === 5) {
          setMoreText('加载更多...')
        } else {
          setMoreText('没有更多了')
        }
        setUpkeepList([...upkeepList, ...res.payload])
      })
    }
  }

  // 点击复制元素中的代码
  const copyCode = (code: string) => {
    navigator.clipboard
      .writeText(code)
      .then(() => {
        alert('文本已复制到剪贴板!')
      })
      .catch((err) => {
        console.error('复制失败:', err)
        alert('复制失败，请手动复制！')
      })
  }

  return (
    <UpkeepWrapper onScroll={scrollPageHandle}>
      {/* 渲染upkeep列表 */}
      {renderUpkeepList()}
      <div className="more">{moreText}</div>
      {/* 抽屉 */}
      <LtDrawer
        open={open}
        bgclor={themeColor}
        direction="right"
        size="65vw"
        onClose={() => setOpen(false)}
      >
        <UpkeepDetailWrapper>
          <div className="mian_title">
            <h3 className="text">{detail.title}</h3>
            <span className="time">{formatTime(detail.created_at)}</span>
          </div>
          <div className="detail_desc">
            <span className="mian_desc">{detail.desc}</span>
          </div>
          {detail.content?.map((m: any, index: number) => {
            return (
              <div key={index} className="content">
                {m.subTitle && <h5 className="sub_title">{m.subTitle}</h5>}
                {m.desc && <p className="sub_desc">{m.desc}</p>}
                {m.code && (
                  <div className="code">
                    <div className="sub_code">
                      <SyntaxHighlighter language="javascript">{m.code}</SyntaxHighlighter>
                      <span className="copy" onClick={() => copyCode(m.code)}>
                        点击复制
                      </span>
                    </div>
                  </div>
                )}
                {m.image && (
                  <div className="image_list">
                    {m.image.map((img: any, index: number) => {
                      return <img key={index} src={img} alt="" />
                    })}
                  </div>
                )}
              </div>
            )
          })}
        </UpkeepDetailWrapper>
      </LtDrawer>
    </UpkeepWrapper>
  )
})

export default Upkeep
